/*
 * Map panel is an editing panel which allows you to draw a polygon and set its center
 * Use it as a normal panel
 * use the getValues method to return the vecotr features of polygon and center {polygon: feature, center: feature}
 */
Ext.ns('App', 'App.control', 'App.util');



App.control.mapPanel = Ext.extend(GeoExt.MapPanel, {
	map: null,
	polygon_layer: null,
	center_layer: null,
	/*
	 *  load the polygon and the center
	 *  polygon string, geojson format
	 *  pt array [x,y]
	 */
	load: function(polygon, pt){
		//add polygon
		if (polygon!=''){
			var geojson_format = new OpenLayers.Format.GeoJSON();
            var geom = geojson_format.read(polygon);
            var geom = geom[0].geometry.transform(new OpenLayers.Projection("EPSG:4326"), new OpenLayers.Projection("EPSG:900913"));
			this.polygon_layer.removeAllFeatures();
			this.polygon_layer.addFeatures([new OpenLayers.Feature.Vector(geom)]);
		}
		
		//add point
		if (pt){
			var pt =  new OpenLayers.Geometry.Point(pt[x], pt[y]);
			var pt = pt.transform(new OpenLayers.Projection("EPSG:4326"), new OpenLayers.Projection("EPSG:900913"));
			this.center_layer.addFeatures([new OpenLayers.Feature.Vector(pt)])
		}
	},
	/*
	 * return the geometry of the polygon and the center
	 */
	getValues: function(){
		var polygon = null;
		var center = null;
		if (this.polygon_layer && this.center_layer) {
			if (this.polygon_layer.features.length==1){
				polygon = this.polygon_layer.features[0]
			} 
			if (this.center_layer.features.length==1){
				center = this.center_layer.features[0]
			} 
		} 
		return {polygon: polygon, center: center}
		
	},
	
	/*
	 * create a map with all the layers
	 */
    buildMap: function(){
    
        var map = new OpenLayers.Map();
        
        //base maps    
        var gphy = new OpenLayers.Layer.Google("Google Physical", {
            type: google.maps.MapTypeId.TERRAIN
        });
        var gmap = new OpenLayers.Layer.Google("Google Streets", // the default
        {
            numZoomLevels: 20,
            streetViewControl: false
        });
        var ghyb = new OpenLayers.Layer.Google("Google Hybrid", {
            type: google.maps.MapTypeId.HYBRID,
            numZoomLevels: 20
        });
        var gsat = new OpenLayers.Layer.Google("Google Satellite", {
            type: google.maps.MapTypeId.SATELLITE,
            numZoomLevels: 22,
            streetViewControl: false
        });
        
        
        
        
        var osm = new OpenLayers.Layer.OSM();
        
        map.addLayers([gmap, osm, gphy,  ghyb, gsat]);
        
        //vector layer
        
        var polygon_layer = new OpenLayers.Layer.Vector("polygon");        
        
        
        var center_layer = new OpenLayers.Layer.Vector("center", {
            styleMap: new OpenLayers.StyleMap(new OpenLayers.Style({
                fillColor: 'red',
                pointRadius: '5'
            }))
        });
        
        map.addLayers([center_layer, polygon_layer]);
        
        //layer switch
        map.addControl(new OpenLayers.Control.LayerSwitcher());
        
        //pass to global
        this.map = map;
        this.polygon_layer = polygon_layer;
        this.center_layer = center_layer;
    },
    /*
     * Create the toolbar
     */
	buildToolbar: function(){
    	var map, polygon_layer, center_layer;
		map = this.map;
		polygon_layer = this.polygon_layer;
		center_layer = this.center_layer;
    
        var ctrl, toolbarItems = [], action, actions = {};
        //pan
        action = new GeoExt.Action({
            text: "Pan",
            iconCls: 'icon-pan',
            control: new OpenLayers.Control.Navigation(),
            map: map,
            // button options
            toggleGroup: "draw",
            allowDepress: false,
            pressed: true,
            tooltip: "navigate",
            // check item options
            group: "draw",
            checked: true
        });
        
        actions["nav"] = action;
        toolbarItems.push(action);
        
        //draw polygon
        action = new GeoExt.Action({
            text: "Draw Impact Area",
            iconCls: 'icon-draw-polygon',
            control: new OpenLayers.Control.DrawFeature(polygon_layer, OpenLayers.Handler.Polygon),
            map: map,
            // button options
            toggleGroup: "draw",
            allowDepress: false,
            tooltip: "draw polygon, double-click to finish",
            // check item options
            group: "draw"
        });
        
        actions["drawpolygon"] = action;
        toolbarItems.push(action);
        
        //edit
        action = new GeoExt.Action({
            text: "Edit Polygon",
            iconCls: 'icon-editfeature',
            control: new OpenLayers.Control.ModifyFeature(polygon_layer),
            map: map,
            // button options
            toggleGroup: "draw",
            allowDepress: false,
            tooltip: "Click on polgon to start editing",
            // check item options
            group: "draw"
        
        });
        actions["edit"] = action;
        toolbarItems.push(action);
        
//        //select tool 
//        action = new GeoExt.Action({
//            text: "Select",
//            iconCls: 'icon-select',
//            control: new OpenLayers.Control.SelectFeature(App.polygon_layer, {
//                type: OpenLayers.Control.TYPE_TOGGLE,
//                hover: false
//            }),
//            map: map,
//            // button options
//            //enableToggle: true,
//            gruop: 'draw',
//            toggleGroup: "draw",
//            tooltip: "Click on polygon to select"
//        });
//        actions["select"] = action;
//        toolbarItems.push(action);
        
        //set marker
        action = new GeoExt.Action({
            text: "Set Marker",
            iconCls: 'icon-point',
            control: new OpenLayers.Control.DrawFeature(this.center_layer, OpenLayers.Handler.Point),
            map: map,
            // button options
            toggleGroup: "draw",
            allowDepress: false,
            tooltip: "Click on the map to set the center of the impact area.",
            // check item options
            group: "draw"
        });
        
        actions["drawcenter"] = action;
        toolbarItems.push(action);
        
        //delete
        action = new GeoExt.Action({
            text: 'Delete',
            iconCls: 'icon-deletevector',
            handler: function(){
                center_layer.removeAllFeatures();
				polygon_layer.removeAllFeatures();
                
                
            }
            
        })
        
        toolbarItems.push(action);
        toolbarItems.push("-");
        
        // Navigation history - two "button" controls
        ctrl = new OpenLayers.Control.NavigationHistory();
        map.addControl(ctrl);
        
        action = new GeoExt.Action({
            text: "previous",
            control: ctrl.previous,
            iconCls: 'icon-zoom-previous',
            disabled: true,
            tooltip: "previous in history"
        });
        
        actions["previous"] = action;
        toolbarItems.push(action);
        
        action = new GeoExt.Action({
            text: "next",
            control: ctrl.next,
            iconCls: 'icon-zoom-next',
            disabled: true,
            tooltip: "next in history"
        });
        actions["next"] = action;
        toolbarItems.push(action);
        
        
        
        return toolbarItems;
    },
    initComponent: function(){
		//build the map, get App.map, ... initialized
        this.buildMap();
        var map = this.map;
        var config = {
            
            center: new OpenLayers.LonLat(-83.019919, 40.001405).transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject()),
            zoom: 15,
            tbar: this.buildToolbar()
        
        
        }; // eo config object
        // apply config
        Ext.apply(this, Ext.apply(this.initialConfig, config));
        
        App.control.mapPanel.superclass.initComponent.apply(this, arguments);
        var center_layer = this.center_layer;
        //register events
        this.polygon_layer.events.on({
			//only one feature will be kept
            'beforefeatureadded': function(feature){
                if (this.features.length > 0) {
                    this.removeAllFeatures();
                }
            },
			//update the center location
            'featureadded': function(feature){
                var pt = new OpenLayers.Feature.Vector(feature.feature.geometry.getCentroid());
                center_layer.addFeatures([pt])
            },
			//update the center location
            'afterfeaturemodified': function(feature){
                var pt = new OpenLayers.Feature.Vector(feature.feature.geometry.getCentroid());
                center_layer.addFeatures([pt])
            }
            
        });
        
        this.center_layer.events.on({
        //only one center is kept
            'beforefeatureadded': function(feature){
                if (this.features.length > 0) {
                    this.removeAllFeatures();
                }
            }
        })
    } // eo function initComponent
    //    ,onRender: function(){
    //        this.store.load();
    //        
    //        App.control.mapField.superclass.onRender.apply(this, arguments);
    //    } // eo function onRender
});

Ext.reg('mappanel', App.control.mapPanel);
